<?php
include_once("../includes/common.php");
include_once("../class/User.class.php");
include_once("../class/Explore.class.php");
include_once("../class/Action.class.php");
require_once("../islogin.php");

if ($islogin!=1){
    header('Location: /login.php');
    exit;
}

$menuavatar = !$user_info["message"]["avatar"] ? "/data/avatar/default.jpg" : $user_info["message"]["avatar"];

$setVparam = $_GET['type'] ?? '';
$allowedValues = [
    'like' => [
        'title' => '我的点赞笔记',
        'view' => 4
    ],
    'star' => [
        'title' => '我的收藏笔记',
        'view' => 5
    ],
    'nocheck' => [
        'title' => '待审笔记',
        'view' => 6
    ],
    'cantcheck' => [
        'title' => '违规笔记',
        'view' => 7
    ]
];
$liketype = 0;

if (array_key_exists($setVparam, $allowedValues)) {
    $pageName = $allowedValues[$setVparam]['title']; // 根据 $get 设置标题
    $history_type = $allowedValues[$setVparam]['view']; // 获取对应的 view 值
}else{
    $pageName = "笔记列表"; // 根据 $get 设置标题
    $info_type = 1; // 获取对应的 view 值
}

if($history_type==6){
    $info_type = 2;
    $history_type = null;
}

if($history_type==7){
    $info_type = 3;
    $history_type = null;
}

if ($history_type == 5) {
    $liketype = 1;
}

if(!$pageName){
    exit('error pagename');
}

//初始化类处
$explore = new Explore();
$action = new Action();


//构造page
$nowPage = $_GET['page'] ?? 1;
if($nowPage<0){
    exit('page error');
}
$pageNum = 8;
$totalPage = 0;

// 获取当前 URL
$currentUrl = $_SERVER['REQUEST_URI'];
// 解析当前 URL
$parsedUrl = parse_url($currentUrl);
$queryParams = [];
if (isset($parsedUrl['query'])) {
    parse_str($parsedUrl['query'], $queryParams);
}

// 判断 $nowPage 是否为整数
if (!filter_var($nowPage, FILTER_VALIDATE_INT)||$nowPage==0) {
    exit(); // 如果不是整数，退出并显示消息
}
//浏览记录页面
if ($info_type==1){
    $info_info = json_decode($explore->profileNotes($user_info['message']['user_id'],$pageNum,$nowPage),true);
    if(!$info_info){
        $info_info = array();
    }
    //var_dump($info_info);
    $totalPage = $explore->getTotalPageProfileNotes($user_info['message']['user_id'],$pageNum);
    //$apiType = 'info';
}elseif ($history_type==4||$history_type==5){
    $info_info = json_decode($explore->likeNotes($user_info['message']['user_id'],$pageNum,$nowPage,$liketype),true);
    if(!$info_info){
        $info_info = array();
    }

    $totalPage = $explore->getTotalPagelikeNotes($user_info['message']['user_id'],$pageNum,$liketype);
    //$apiType = 'info';
}elseif ($info_type==2||$info_type==3){
    $sodataArray = json_decode($explore->profileNotes($user_info['message']['user_id'],1000,1),true);

    $searchKeyword = ($info_type == 2) ? 0 : 2;

    if ($_GET['so']) {
        $filteredResults = array_filter($sodataArray, function($item) use ($searchKeyword) {
            // 精准匹配 $item['check_result'] 是否等于 0，并且模糊匹配 $_GET['so'] 和 $item['title']
            return $item['check_result'] === (string)$searchKeyword && stripos($item['title'], $_GET['so']) !== false;
        });
    }else{
        $filteredResults = array_filter($sodataArray, function($item) use ($searchKeyword) {
            // 精准匹配 $item['check_result'] 是否等于 0
            return $item['check_result'] === (string)$searchKeyword; // 精准匹配 0，确保类型一致
        });
    }

    $filteredResults = array_values($filteredResults);  //编制索引
    $info_info = $filteredResults;
    //var_dump($info_info);
    if(!$info_info){
        $info_info = array();
    }
    $totalPage = 1;
}


if($_GET['so']){
    $totalPage = 1;
    $searchKeyword = $_GET['so'] ?? ''; // 获取搜索关键词

    if($info_type==1){
        $sodataArray = json_decode($explore->searchUserNotes('',$user_info['message']['user_id'],$searchKeyword,1000),true);
        //var_dump($explore->searchUserNotes('',$user_info['message']['user_id'],$searchKeyword,1000));
        if($info_info){
            $info_info = $sodataArray;
        }
    }

    if($history_type==4||$history_type==5){
        $sodataArray = json_decode($explore->likeNotes($user_info['message']['user_id'],1000,1,$liketype),true);
        $filteredResults = array_filter($sodataArray, function($item) use ($searchKeyword) {
            return stripos($item['title'], $searchKeyword) !== false; // 不区分大小写的模糊匹配
        });
        $filteredResults = array_values($filteredResults);  //编制索引
        if($info_info){
            $info_info = $filteredResults;
        }
    }


}

// 构建链接 - 必须放最后得等上面查好总页数
$nextPage = $nowPage + 1 > $totalPage ? $totalPage : $nowPage + 1;
$prevPage = $nowPage - 1 < 1 ? 1 : $nowPage - 1;
// 更新 page 参数
$queryParams['page'] = $nextPage; // 对于下一页
$nextPageLink = $parsedUrl['path'] . '?' . http_build_query($queryParams);

// 更新 page 参数
$queryParams['page'] = $prevPage; // 对于上一页
$prevPageLink = $parsedUrl['path'] . '?' . http_build_query($queryParams);


if (isset($_GET['del'])) {
    // 在这里执行删除操作
    $explore->hideNote($user_info['message']['user_id'], $_GET['del']);
    // 删除成功后，跳转回来路页面
    $referrer = $_SERVER['HTTP_REFERER']; // 获取来路页面的 URL
    header("Location: $referrer"); // 重定向到来路页面
    exit();
}

if (isset($_GET['cancel'])) {
    $explode = explode('|', $_GET['cancel']);

    // 在这里执行删除操作
    $action->userLikeAction($user_info['message']['user_id'], $explode[0], null, $explode[1]);
    // 删除成功后，跳转回来路页面
    $referrer = $_SERVER['HTTP_REFERER']; // 获取来路页面的 URL
    header("Location: $referrer"); // 重定向到来路页面
    exit();
}

?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <?php require_once('head.php'); ?>
</head>
<body>
    
<!--==================== Preloader Start ====================-->
  <div class="preloader">
    <div class="loader"></div>
  </div>
<!--==================== Preloader End ====================-->

<!--==================== Sidebar Overlay End ====================-->
<div class="side-overlay"></div>
<!--==================== Sidebar Overlay End ====================-->

<?php require_once('user_menu.php'); ?>

    <div class="dashboard-main-wrapper">
        <?php require_once('top_navbar.php'); ?>
        <div class="dashboard-body">

            <!-- Recommended Start -->
            <div class="card">
                <div class="card-body">

                    <div class="mb-20 flex-between flex-wrap gap-8">
                        <h4 class="mb-0"><?php echo $pageName;?> <?php echo $nowPage?>/<?php echo $totalPage?> 页</h4>

                    </div>
                    
                    <div class="row g-20">
                        <?php for ($i = 0; $i < count($info_info); $i++) { ?>
                        <div class="col-xxl-3 col-lg-4 col-sm-6">
                            <div class="card border border-gray-100">
                                <div class="card-body p-8">
                                    <a href="/explore.php?id=<?php echo $info_info[$i]['note_id'];?>" class="bg-main-100 rounded-16 overflow-hidden text-center mb-8 h-164 flex-center">
                                        <img src="<?php echo (getFirstValidImage($info_info[$i]['image']) ?: '/static/img/default.jpg');?>" alt="Course Image" class="cover-img">
                                    </a>
                                    <div class="p-8">
                                        <?php
                                        $check_result = $info_info[$i]['check_result'];

                                        switch ($check_result) {
                                            case 0:
                                                echo '<span class="text-13 py-2 px-10 rounded-pill bg-warning-50 text-warning-600 mb-16">审核中</span>';
                                                break;
                                            case 1:
                                                echo '<span class="text-13 py-2 px-10 rounded-pill bg-success-50 text-success-600 mb-16">审核通过</span>';
                                                break;
                                            case 2:
                                                echo '<span class="text-13 py-2 px-10 rounded-pill bg-danger-50 text-danger-600 mb-16">笔记违规</span>';
                                                break;
                                            default:
                                                echo '<span class="text-13 py-2 px-10 rounded-pill bg-secondary-50 text-secondary-600 mb-16">未知状态</span>';
                                                break;
                                        }
                                        echo $info_info[$i]['type'] == 1 ? '<span style="margin-left: 10px" class="text-13 py-2 px-10 rounded-pill bg-main-50 text-main-600 mb-16">视频</span>' : '<span style="margin-left: 10px" class="text-13 py-2 px-10 rounded-pill bg-pink-50 text-pink-600 mb-16">笔记</span>';
                                        ?>

                                        <h5 class="mb-8"><a href="/explore.php?id=<?php echo $info_info[$i]['note_id'];?>" class="hover-text-main-600"><?php echo $info_info[$i]['title'];?></a></h5>

                                        <div class="flex-align gap-8">
                                            <div class="flex-align gap-4">
                                                <span class="text-sm text-main-600 d-flex"><i class="ph ph-clock"></i></span>
                                                <span class="text-13 text-gray-600"><?php echo formatNoteTime($info_info[$i]['note_time']);?></span>
                                            </div>
                                            <div class="flex-align gap-4">
                                                <span class="text-sm text-main-600 d-flex"><i class="ph ph-chats-circle"></i></span>
                                                <span class="text-13 text-gray-600"><?php echo $info_info[$i]['statistics']['comments_count'];?></span>
                                            </div>
                                        </div>

                                        <div class="flex-align gap-8 flex-wrap mt-20">
                                            <img src="<?php echo '/' . ltrim($info_info[$i]["user"]["avatar"] ?: '/data/avatar/default.jpg', '/'); ?>" class="w-28 h-28 rounded-circle object-fit-cover" alt="User Image">
                                            <div>
                                                <span class="text-gray-600 text-13">作者 <a href="/profile.php?id=<?php echo $info_info[$i]["user"]['user_id'];?>" class="fw-semibold text-gray-700 hover-text-main-600 hover-text-decoration-underline"><?php echo $info_info[$i]["user"]['nickname'];?></a> </span>
                                            </div>
                                        </div>

                                        <div class="flex-between gap-4 flex-wrap mt-20">
                                            <div class="flex-between gap-4">
                                                <span class="text-15 fw-bold text-danger-600 d-flex"><i class="<?php echo ($history_type == 4) ? 'ph-fill' : 'ph';?> ph-heart"></i></span>
                                                <span class="text-13 fw-bold text-gray-600"><?php echo $info_info[$i]['statistics']['likes_count'];?></span>
                                            </div>
                                            <div class="flex-between gap-4">
                                                <span class="text-15 fw-bold text-warning-600 d-flex"><i class="<?php echo ($history_type == 5) ? 'ph-fill' : 'ph';?> ph-star"></i></span>
                                                <span class="text-13 fw-bold text-gray-600"><?php echo $info_info[$i]['statistics']['favorites_count'];?></span>
                                            </div>
                                        </div>
                                        <div class="flex-between gap-4 flex-wrap mt-20">
                                            <?php if (!$history_type){?>
                                                <a href="edit.php?nid=<?php echo $info_info[$i]['note_id'];?>" class="btn btn-outline-main rounded-pill py-3 flex-center ">
                                                    编辑 <span class="d-flex text-xl"><i class="ph ph-pencil-simple"></i></span>
                                                </a>
                                            <?php }?>
                                            <a href="/explore.php?id=<?php echo $info_info[$i]['note_id'];?>" class="btn btn-outline-main rounded-pill py-3 flex-center">
                                                查看 <span class="d-flex text-xl"><i class="ph ph-arrow-right"></i></span>
                                            </a>
                                            <?php if ($history_type){?>
                                                <a onclick="return confirm('确定要取消<?php echo ($history_type == 4) ? '喜欢' : '收藏';?>这条笔记吗？');" href="?cancel=<?php echo $info_info[$i]['note_id'];?>|<?php echo $liketype?>" class="btn btn-outline-main rounded-pill py-3 flex-center ">
                                                    取消 <span class="d-flex text-xl"><i class="ph ph-receipt-x"></i></span>
                                                </a>
                                            <?php }?>
                                        </div>
                                        <?php if (!$history_type){?>
                                            <div class="flex-center gap-4 flex-wrap mt-20">
                                                <a onclick="return confirm('确定要删除这篇笔记吗？');" href="?del=<?php echo $info_info[$i]['note_id'];?>" class="btn btn-danger rounded-pill py-3 flex-center">
                                                    <span class="d-flex text-xl"><i class="ph ph-trash"></i></span> 删除
                                                </a>
                                            </div>
                                        <?php }?>


                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php } ?>
                    </div>

                    <?php if(!isset($_GET['so'])){?>

                        <div class="flex-between flex-wrap gap-8 mt-20">
                            <a href="<?php echo $prevPageLink; ?>" class="btn btn-outline-gray rounded-pill py-9 flex-align gap-4">
                                <span class="d-flex text-xl"><i class="ph ph-arrow-left"></i></span>
                                上一页
                            </a>

                            <?php if($totalPage>10){?>
                                <ul class="pagination flex-align flex-wrap">
                                    <?php include 'pagination.php'; ?>
                                </ul>
                            <?php }?>

                            <a href="<?php echo $nextPageLink; ?>" class="btn btn-outline-main rounded-pill py-9 flex-align gap-4">
                                下一页 <span class="d-flex text-xl"><i class="ph ph-arrow-right"></i></span>
                            </a>
                        </div>
                    <?php }?>
                    
                </div>
            </div>
            <!-- Recommended End -->
        </div>
        <?php require_once('footer.php'); ?>
    </div>


<?php require_once('foot.php'); ?>


    </body>
</html>